import { connect } from 'dva'
import { Table, Pagination, Popconfirm } from 'antd'
import { routerRedux } from 'dva/router'
import styles from './index.css'
import UserModal from './components/UserModal'
import { Link } from 'react-router-dom'
function UsersList ({ dispatch, location, list: dataSource, loading, total, page  }) { 
	let { pathname, query } = location  //location对象 会存放当前页面的路由信息
	function deleteHandler (id) {
		dispatch({
			type: 'usersList/remove',
			payload: id,
		})
	}

	function pageChangeHandler (page) {
		console.log(page)
		dispatch(routerRedux.push({
			pathname,
			query: { 
				page ,
			},
		}))
	}

	function onShowSizeChange (page, pageSize) {
		dispatch(routerRedux.push({
			pathname,
			query: {
				...query,
				page,
				pageSize,
			},
		}))
	}

	function editHandler (id, values) {
		dispatch({
			type: 'usersList/patch',
			payload: { id, values },
		})
	}

	const rowSelection = {
		onChange: (selectedRowKeys, selectedRows) => {
		  console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
		},
		getCheckboxProps: record => ({
		  disabled: record.name === 'Disabled User', // Column configuration not to be checked
		  name: record.name,
		}),
	}

	const columns = [
		{
			title: '姓名',
			dataIndex: 'name',
			editable: true,
		},
		{
			title: '性别',
			render (text , record){
				let sex = ``
				if(record.text === "1") sex = `男` 
				if(record.text === "2") sex = `女` 
				return sex
			},
			editable: true,
		},
		{
			title: '年龄',
			dataIndex: 'age',
			editable: true,
		},
		{
			title: '地址',
			dataIndex: 'address',
			width: '40%',
			editable: true,
		},
		{
			title: 'Operation',
			key: 'operation',
			render: (text, record) => (
				<span className={styles.operation}>
					<UserModal record={record} onOk={editHandler.bind(null, record.key)}>
						<a>Edit</a>
					</UserModal>
					<Link to={`usersList/detail/${record.key}`}>用户详情</Link>
					<Popconfirm title="Confirm to delete?" onConfirm={deleteHandler.bind(null, record.key)}>
						<a href="">Delete</a>
					</Popconfirm>
				</span>
			),
		},
	]
	return (
		<div className={styles.normal}>
			<div>
			<Table
				loading={loading}
				rowSelection={rowSelection} //选择监听
				columns={columns}
				dataSource={dataSource}
				rowKey={record => record.key}
				pagination={false}
			/>
			<Pagination
				className="ant-table-pagination"
				total={total}
				current={page}
				onChange={pageChangeHandler}
				onShowSizeChange={onShowSizeChange}
			/>
			</div>
		</div>
	)
}

function mapStateToProps (state){
	const { total, page } = state.usersList.pageState
	const { list } = state.usersList
	return {
		list,
		total,
		page,
		loading: state.loading.models.usersList,
	}
}

export default connect(mapStateToProps)(UsersList)